package ch.fhnw.qualiscan.application.modals;

import java.util.ArrayList;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.models.RoleModel;
import ch.fhnw.qualiscan.application.models.SurveyModel;
import ch.fhnw.qualiscan.application.models.UserModel;
import ch.fhnw.qualiscan.application.pages.tabs.EditSurveyTab2Coordinator;
import ch.fhnw.qualiscan.core.Modal;
import ch.fhnw.qualiscan.core.db.helpers.addUserToSurveyArgs;
import ch.fhnw.qualiscan.core.db.helpers.participantsTableArgs;
import ch.fhnw.qualiscan.core.db.pojos.Role;
import ch.fhnw.qualiscan.core.db.pojos.Survey;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.db.pojos.User;
import ch.fhnw.qualiscan.core.helpers.EmailHelper;
import ch.fhnw.qualiscan.core.libraries.NotificationLib;

import com.vaadin.data.Validator.EmptyValueException;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.TextField;

import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class AddParticipantToSurvey extends Modal{
	
	private Form participantForm;
	private TextField email;
	private NativeSelect roleSelect; 
	//private CheckBox invitationMail;	TODO outcomment if you want to decide whether to send a invitation or not
	private Button saveButton;
	private Button discardButton;
	private Survey survey;
	private UserModel userModel;
	private RoleModel roleModel;
	private SurveyModel surveyModel;
	private EditSurveyTab2Coordinator caller;
	
	public AddParticipantToSurvey(Survey survey, EditSurveyTab2Coordinator caller) {
		setCaption(TM.get("addparticipant.title"));
		this.survey = survey;
		userModel = new UserModel();
		roleModel = new RoleModel();
		surveyModel = new SurveyModel();
		this.caller = caller;
		buildLayout();
	}
	
	/**
	 * constructor for adding a expert to the survey via pvaluation page.
	 * @param survey to which the participant should be added.
	 */
	public AddParticipantToSurvey(Survey survey) {
		this.survey = survey;
		userModel = new UserModel();
		roleModel = new RoleModel();
		surveyModel = new SurveyModel();
		this.caller = null;
		
		setCaption(TM.get("evaluation.invite"));
		buildLayout();
	}
	
	public void buildLayout() {
		participantForm = new Form();
		participantForm.setImmediate(true);
		
		email = new TextField(TM.get("user.email"));
		email.setRequired(true);
		email.setRequiredError(TM.get("user.error.email"));
		email.addValidator(new EmailValidator(TM.get("addparticipant.form.emailinvalid")));
		email.setWidth("300px");
		email.setCursorPosition(0);
		
		roleSelect = new NativeSelect(TM.get("user.role"));
		roleSelect.setRequired(true);
		roleSelect.setRequiredError(TM.get("user.error.role"));
		
		//invitationMail = new CheckBox(TM.get("addparticipant.form.email"));
		
		List<Role> roleList = roleModel.getParticipantRoles();
		
		if(this.caller == null) {
			Role expertRole = roleModel.getRoleById(Config.EXPERT_ID);
			roleSelect.addItem(expertRole);
			roleSelect.setItemCaption(expertRole, userModel.getRoleText(expertRole, userSession.getLanguage()).getTitle());
			roleSelect.select(expertRole);
		} else 
		for (int i = 0; i < roleList.size(); i++) {
			roleSelect.addItem(roleList.get(i));
			roleSelect.setItemCaption(roleList.get(i), userModel.getRoleText(roleList.get(i), userSession.getLanguage()).getTitle());
		}
		
		participantForm.addField("email", email);
		participantForm.addField("role", roleSelect);
		//participantForm.addField("invitationmail", invitationMail);
		
		HorizontalLayout buttonBar = new HorizontalLayout();
		buttonBar.setSpacing(true);
		buttonBar.setMargin(true, false, false, false);
		
		participantForm.getFooter().addComponent(buttonBar);
		
		saveButton = new Button(TM.get("action.save"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				try {
					participantForm.commit();
					
					User newUser = new User();
					newUser.setEmail((String) email.getValue());
					
					List<addUserToSurveyArgs> autsaList = new ArrayList<addUserToSurveyArgs>();
					addUserToSurveyArgs autsa = new addUserToSurveyArgs(newUser, (Role)roleSelect.getValue());
					autsaList.add(autsa);
					
					List<SurveyUserRole> surList = surveyModel.addUsersToSurvey(autsaList, survey);
					if (surList.size() > 0) {
						SurveyUserRole sur = surList.get(0);
						
						if(caller != null) {
							participantsTableArgs pta = new participantsTableArgs(sur, sur.getUser().getFirstname(), sur.getUser().getLastname(), sur.getUser().getEmail(), userModel.getRoleText(sur.getRole(), userSession.getLanguage()).getTitle());
							caller.tableContainer.addBean(pta);
						}
						
						EmailHelper eh = new EmailHelper();
						
						String inviter = userSession.getFirstname() + " " + userSession.getLastname()+"";

						if (sur.getRole().getId() == Config.EXPERT_ID) {
							eh.sendInvitationMail(sur, TM.get("email.invitationtext.expert", inviter, sur.getSurvey().getTitle()));
						}
						else {
							eh.sendInvitationMail(sur, TM.get("email.invitationtext",inviter, sur.getSurvey().getTitle()));
						}

						roleSelect.setValue(null);
						email.setValue("");
						NotificationLib.showSuccess(TM.get("addparticipant.added"), null);
					}
					else {
						NotificationLib.showError(TM.get("addparticipant.error.userexists.title"), null);
						roleSelect.setValue(null);
						email.setValue("");
					}
					
					participantForm.discard();
					closeModal();
					
				}
				catch (EmptyValueException e) {
					
				}
				catch (InvalidValueException e) {
					
				}		
			}
		});
		saveButton.setIcon(Config.ICON_TICK);
		
		discardButton = new Button(TM.get("action.cancel"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				AddParticipantToSurvey apts = (AddParticipantToSurvey) event.getButton().getData();
				apts.close();
			}
		});
		discardButton.setData(this);
		discardButton.setIcon(Config.ICON_CANCEL);
		
		buttonBar.addComponent(saveButton);
		buttonBar.addComponent(discardButton);
		
		addComponent(textHelper.p(TM.get("addparticipant.form.title")));
		addComponent(participantForm);
	}
}
